import { fetchEventSource } from "@microsoft/fetch-event-source";

const baseUrl = "https://api.coze.cn/v3";
const API_KEY =
  "pat_XKj6MSqAfqdm8RbjvfdnrplPhNnfYwjsr914mxT7nBnrge9UeZ4Qg5Yu4khMbTkH";

const getRealtimeMessage = (conversation_id, queryContent, getMessageFn) => {
  const data = {
    bot_id: "7444784944209330226",
    user_id: "123",
    conversation_id: `${conversation_id}`,
    stream: true,
    additional_messages: [
      {
        role: "user",
        content: `${queryContent}`,
        content_type: "text",
      },
    ],
  };

  const ctrlAbout = new AbortController();
  fetchEventSource(`${baseUrl}/chat`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json", // 文本返回格式
    },
    body: JSON.stringify(data),
    signal: ctrlAbout.signal,
    openWhenHidden: true, // 在浏览器标签页隐藏时保持与服务器的EventSource连接
    onmessage(res) {
      // 操作流式数据
      //console.log(res);
      getMessageFn(res);
    },
    onclose(res) {
      // 关闭流
      console.log("onclose");
    },
    onerror(error) {
      // 返回流报错
    },
  });
};

export function GetRealtimeMessage(
  conversation_id,
  queryContent,
  getMessageFn
) {
  return getRealtimeMessage(conversation_id, queryContent, getMessageFn);
}
